package com.gears_software.sxdc.dccx.ui.activity;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.ICPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.IMemberFinder;
import com.gears_software.sxdc.dccx.data.finder.RequestUrl;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.MemberModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.Seat;
import com.gears_software.sxdc.dccx.data.model.request.RReserveModel;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.gears_software.sxdc.dccx.ui.util.ShowSeat;
import com.gears_software.sxdc.dccx.ui.util.ShowTime;
import com.gears_software.sxdc.dccx.ui.util.ShowUnivalence;
import com.github.mzule.activityrouter.annotation.Router;
import com.sdsmdg.tastytoast.TastyToast;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.CheckedChange;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by SunMuran on 2017/7/27.
 * 马上预定
 */
@Router(value = "yuding", isEActivity = true)
@EActivity(R.layout.immediately_reserve)
public class ImmediatelyReserveActivity extends Activity {
    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView tv_reserve_seat_icon;
    @ViewById
    TextView tv_riding_time_icon;
    @ViewById
    TextView tv_selector_univalence;
    @ViewById
    TextView tv_selector_reserve_seat;
    @ViewById
    TextView tv_riding_time;
    @ViewById
    EditText edit_phone;
    @ViewById
    EditText et_riding_address;
    @ViewById
    EditText et_other_description;
    @ViewById
    RelativeLayout rl_univalence;
    @ViewById
    RelativeLayout rl_reserve_seat;
    @ViewById
    RelativeLayout rl_riding_time;
    @ViewById
    CheckBox checkbox;
    @ViewById
    Button btn_submit;
    @ViewById
    Button btn_cancel;

    @RestService
    ICPOrderFinder icpOrderFinder;
    @RestService
    IMemberFinder memberFinder;
    @Bean
    GearsErrorHandler errorHandler;
    MaterialDialogProgress progress;
    String departtime;
    int seat;
    String orderid;
    OptionsPickerView pickerView;
    TimePickerView timePickerView;
    List<Seat> seatList = new ArrayList<Seat>();
    MemberModel memberModel;

    @AfterViews
    void created() {
        actionbar_title.setText("马上预定");
        icpOrderFinder.setRestErrorHandler(errorHandler);
        memberFinder.setRestErrorHandler(errorHandler);
        initIconfont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        progress = new MaterialDialogProgress(this);
        progress.show("正在加载...");
        String price = getIntent().getStringExtra("price");
        departtime = getIntent().getStringExtra("departtime");
        seat = Integer.valueOf(getIntent().getStringExtra("seat"));
        orderid = getIntent().getStringExtra("orderid");
//        initTimePicker();
        if (departtime != null && !departtime.equals("")) {
            tv_riding_time.setText(departtime);
        }
        if (!price.equals("")) {
            tv_selector_univalence.setText(price);
        }
        if (seat > 0) {
            for (int i = 0; i < seat; i++) {
                seatList.add(new Seat(i + 1, String.valueOf(i + 1)));
            }
            pickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    tv_selector_reserve_seat.setText(seatList.get(options1).getPickerViewText());
                }
            }).setLineSpacingMultiplier(2).build();
            pickerView.setPicker(seatList);
        }
        getCurrentMember();

    }

    void initTimePicker() {
        Date start = new Date();
        if (departtime != null && !departtime.equals("")) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            try {
                start = format.parse(departtime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        Calendar selectedDate = Calendar.getInstance();
        selectedDate.setTime(start);
        Calendar startDate = Calendar.getInstance();
        startDate.setTime(start);
        startDate.set(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH),
                startDate.get(Calendar.HOUR_OF_DAY), startDate.get(Calendar.MINUTE));
        Calendar endDate = Calendar.getInstance();
        endDate.set(2020, 11, 1);
        //时间选择器
        timePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                tv_riding_time.setText(getTime(date));
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, true, true, false})
                .setLabel("", "", "", "时", "分", "")
                .isCenterLabel(true)
                .setCancelText("取消")
                .setSubmitText("确认")//确认按钮文字
                .setDividerColor(Color.DKGRAY)
//                .setContentSize(18)
                .isCyclic(true)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .setLineSpacingMultiplier(2)
                .build();
    }

    void initIconfont() {
        back_icon.setTypeface(app.iconfont);
        back_icon.setText(R.string.back_icon);
        right_icon.setVisibility(View.GONE);
        tv_reserve_seat_icon.setTypeface(app.iconfont);
        tv_riding_time_icon.setTypeface(app.iconfont);
    }

    @Background
    void getCurrentMember() {
        ResultModel<MemberModel> result = memberFinder.getMember();
        showMemberResult(result);
    }

    @UiThread
    void showMemberResult(ResultModel<MemberModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    memberModel = res.getData();
                    if (memberModel.getDriverphone() != null && !memberModel.getDriverphone().equals("")) {
                        edit_phone.setText(memberModel.getDriverphone());
                    }
                }
            }
        }
        progress.dismiss();
    }

    @Click
    void rl_reserve_seat() {
        if (seatList != null && seatList.size() > 0) {
            pickerView.show();
        }
    }

    @Click
    void btn_submit() {
        if (tv_selector_reserve_seat.getText().toString().equals("")) {
            TastyToast.makeText(this, "请选择乘车座位数", app.SHORT, app.WARNING);
        } else if (et_riding_address.getText().toString().equals("")) {
            TastyToast.makeText(this, "请填写乘车地点", app.SHORT, app.WARNING);
        } else if (edit_phone.getText().toString().equals("")) {
            TastyToast.makeText(this, "请填写乘车人手机号", app.SHORT, app.WARNING);
        } else if (!checkbox.isChecked()) {
            TastyToast.makeText(this, "请先阅读协议和条款", app.SHORT, app.WARNING);
        } else {
//            String yd_departTime = tv_riding_time.getText().toString();
//            int res = departtime.compareTo(yd_departTime);
//            String yd_seat = tv_selector_reserve_seat.getText().toString();
//
//            if (res > 0) {
//                TastyToast.makeText(this, "乘车时间不得晚于车辆出发时间", app.LONG, app.WARNING);
//            } else {
            RReserveModel reserveModel = new RReserveModel();
            reserveModel.setOrderId(orderid);
            reserveModel.setPassengerPhone(edit_phone.getText().toString());
            reserveModel.setrAddress(et_riding_address.getText().toString());
            reserveModel.setSeatNum(tv_selector_reserve_seat.getText().toString());
            reserveModel.setrTime(tv_riding_time.getText().toString());
            reserveModel.setMemo(et_other_description.getText().toString());
            goReserve(reserveModel);
//            }
        }
    }

    @Background
    void goReserve(RReserveModel model) {
        ResultModel<String> res = icpOrderFinder.getReserve(model);
        showResult(res);
    }

    @UiThread
    void showResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "预定信息提交成功，等待司机确认", app.LONG, app.SUCCESS);
                finish();
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    @Click
    void btn_cancel() {
        finish();
    }

    private String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String str = format.format(date);
        return str;
    }
}
